package spring.mvc.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import spring.mvc.bean.Person;
import spring.mvc.dao.PersonDao;
import spring.mvc.dao.PersonDaoImpl;

@Transactional(readOnly = true)
public class PersonDetailService implements UserDetailsService {
	protected static Logger logger = Logger.getLogger("service");
	PersonService personService = new PersonServiceImpl();

	@Override
	public UserDetails loadUserByUsername(String name)
			throws UsernameNotFoundException {
		UserDetails user = null;
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		Person p = personService.getByName(name);
		user = new User(p.getName(), p.getPassword(), enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				getUserAuthorities(p.getRole()));
		return user;
	}

	public Collection<GrantedAuthority> getUserAuthorities(String role) {
		List<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
		// Person p=new Person();
		logger.debug("Grant ROLE_USER to this user");
		if (role.equals("admin")) {
			auth.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		} else if (role.equals("user")) {
			auth.add(new GrantedAuthorityImpl("ROLE_USER"));
		}
		return auth;
	}

}
